package com.haoxuer.discover.bbs.data.dao.impl;

import com.haoxuer.discover.bbs.data.entity.Forum;
import com.haoxuer.discover.data.core.Finder;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.haoxuer.discover.bbs.data.dao.ForumDao;
import com.haoxuer.discover.data.core.CatalogDaoImpl;

/**
* Created by imake on 2017年11月27日09:47:02.
*/
@Repository

public class ForumDaoImpl extends CatalogDaoImpl<Forum, Integer> implements ForumDao {

	@Override
	public Forum findById(Integer id) {
	    if (id==null) {
			return null;
		}
		return get(id);
	}

	@Override
	public Forum save(Forum bean) {

		add(bean);
		
		
		return bean;
	}

    @Override
	public Forum deleteById(Integer id) {
		Forum entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}
	
	@Override
	protected Class<Forum> getEntityClass() {
		return Forum.class;
	}
	
	@Autowired
	public void setSuperSessionFactory(SessionFactory sessionFactory){
	    super.setSessionFactory(sessionFactory);
	}

	@Override
	public Integer updateNums(Integer id) {

		Integer result = 0;
		Forum cur = findById(id);
		do {
			counts(cur);
			cur = cur.getParent();
			result++;
		} while (cur != null);

		return result;
	}

	private void counts(Forum cur) {
		Finder finder = Finder.create();
		finder.append("from ForumPost a where a.forum.lft >= :lft ");
		finder.setParam("lft", cur.getLft());
		finder.append(" and a.forum.rgt <= :rgt");
		finder.setParam("rgt", cur.getRgt());
		Long size = countQuery(finder);
		cur.setNums(size);
	}
}